package org.platform.processor.task;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil;
import org.platform.constant.DiagnoseConst;
import org.platform.dao.mapper.FdDiagnosetaskMapper;
import org.platform.dao.mapper.FdDiagnosetaskTaskMapper;
import org.platform.mo.bussmo.task.TaskCatalog;
import org.platform.mo.db.FdDiagnosetask;
import org.platform.tool.helper.ResourceHelper;
import org.platform.tool.util.FtpClientUtil;
import org.platform.tool.util.TimeUtils;
import org.platform.tool.util.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;


/**
 * 任务诊断处理类
 * <p>
 * 诊断类型:1.任务诊断* 2.故障树诊断 3.测试诊断
 *
 * @author FengJie
 * @date 2018/8/22
 */
@Service
public class TaskDiagnoseProcessor {
    @Autowired
    private ResourceHelper resource;
    @Autowired
    private FdDiagnosetaskMapper diagnoseTaskMapper;
    @Autowired
    private FdDiagnosetaskTaskMapper taskMapper;

    /**
     * 创建任务诊断
     *
     * @param zipFileName 文件名
     * @param xml         文件类型
     */
    public void addTaskDiagnose(String zipFileName, String xml) {
        TaskCatalog taskCatalog = XmlUtils.xmlToBean(xml, TaskCatalog.class, true, "InterFaceFile");
        String planID = taskCatalog.getContent().getScheduleID();
        String ftpPath = taskCatalog.getContent().getPath();

        //登录ftp,并将ftp上的(.zip)文件下载到本地
        FtpClientUtil ftpUtil = FtpClientUtil.getInstance(resource.getFtpIp(), resource.getFtpPort(), resource.getPtpUsername(), resource.getPtpPassword());
        String localFolderPath = resource.getLocalRootDir() + resource.getLocalArchivingDir();
        ftpUtil.downloadFile(ftpPath, localFolderPath, zipFileName);

        String localZipPath = localFolderPath + File.separator + zipFileName;
        //将文件解压  c:\a.zip  (解压后)->   c:\a
        ZipUtil.unzip(localZipPath, new File(localZipPath).getParent(), CharsetUtil.CHARSET_GBK);

        //得到任务号目录
        String path = localFolderPath.substring(0, localFolderPath.lastIndexOf("."));
        //第一层,遍历所有的: 子项序号/作业任务编号
        File[] files = new File(path).listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    String subID = file.getName();
                    FdDiagnosetask diagnoseTask = new FdDiagnosetask();
                    diagnoseTask.setDiagnoseid(subID);
                    //这里设备任务id  计划号_子计划号
                    diagnoseTask.setTaskid(planID);
                    diagnoseTask.setIsmain(0);
                    diagnoseTask.setStatus(DiagnoseConst.DIAGNOSE_STATUS_WAIT);
                    diagnoseTask.setStarttime(TimeUtils.getCurrentTimeMillis());
                    diagnoseTask.setEndtime(0L);
                    diagnoseTaskMapper.insertSelective(diagnoseTask);
                }
            }
        }
    }
}
